package servlets;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.DocumentDAO;
import domain.Document;

public class DownloadFileServlet extends HttpServlet {
	private static final long serialVersionUID = 3305004645714558181L;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String fileId = request.getParameter("fileId");
		Document documento = null;
		try {
			documento = new DocumentDAO().select(Integer.valueOf(fileId));
		} catch (Exception e) {
			e.printStackTrace();
		}
		File file = new File(documento.getPath());
		response.addHeader("Content-Transfer-Coding", "binary");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", -1);
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Content-Length", "" + file.length());
		response.setHeader("Accept-Ranges", "bytes");
		response.setHeader("Cache-Control", " must-revalidate, post-check=0, pre-check=0");
		response.setHeader("Cache-Control", " public");
		String headerContentDisposition = "attachment; filename=\"" + file.getName() + "\"";
		response.addHeader("Content-Disposition", headerContentDisposition);
		String extension = "octet";
		String fname = file.getName();
		int pos = fname.lastIndexOf(".");
		if (pos > -1) {
			if (pos < fname.length()) {
				extension = fname.substring(pos + 1);
			}
		}
		response.setContentType("application/" + extension);
		OutputStream os = response.getOutputStream();
		try {
			FileInputStream fis = new FileInputStream(file);
			byte[] bArray = new byte[512];
			int chRead = -1;
			int z = 0;
			for (int j = 0;; j++, z++) {
				chRead = fis.read(bArray, 0, bArray.length);
				if (chRead < 0) {
					break;
				}
				os.write(bArray, 0, chRead);
			}
			os.flush();
			fis.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
